//
//  ComDynamicBaseVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/11/8.
//  Copyright © 2025 aowang. All rights reserved.
//
import UIKit
import Kingfisher
import JJCollectionViewRoundFlowLayout_Swift
//  描述：
//   固定菜单目录和固定菜单
//   配置菜单目录和配置菜单
//   配置报表  无目录，依附于固定菜单目录和配置菜单目录 以代码形式接入 003001
class ComDynamicBaseVC: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    var refreshDfMenuClosure:(()->())?
    
    
    
    
    lazy var collectionView:UICollectionView = {
       
       
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: getlayout())
     
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.register(FunctionCenterCell.self, forCellWithReuseIdentifier: FunctionCenterCell.identifier)
       
        collectionView.register(FunctionCenterHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FunctionCenterHeader.identifier)
        
        return collectionView
    }()
    private var moduleID = ""
    private var titleS = ""
    
  // 接收3个来源的菜单数组  1 - 配置菜单 2 - 配置报表  3 - 本地菜单
  // 目录结构以配置菜单为主
  // 如果配置报表 ， 本地菜单  和  配置菜单目录相同，则拼接在配置菜单后面，如果没有相同，则自己成立目录
  // 本地菜单  和  动态报表  动态报表提前插入  menupool
  // 目录里的菜单顺序为    配置菜单 -> 配置报表 -> 本地菜单
    var dyArr:[String] = []
    var dyDic:[String : [String]] = [:]
    
    var limitIDS = [String]()// 权限ids数组，处理菜单过滤
    var searchBar:UISearchBar?
    var keyWord = ""
    
    var tempItemList = [(String,[MenuItem])]()
    private var totalItemList = [(String,[MenuItem])]()
    
    var dyArrParam = ""
    var dyDicParam = ""
    // 因为tabbar取值比较早，dic会有变化，所以改为字典取值，保证能取到报表更新后的最新值

    init(title:String,moduleID:String,limitIDS:[String],dyArrParam:String,dyDicParam:String) {
        self.titleS = title
        self.moduleID = moduleID
        self.limitIDS = limitIDS
        self.dyArrParam = dyArrParam
        self.dyDicParam = dyDicParam
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getcolltopMargin() -> CGFloat {
        return 40
    }
    func getlayout() -> JJCollectionViewRoundFlowLayout_Swift {
        // 1.创建layout
        let sectionW = self.view.ks_width - 24
        let layout = JJCollectionViewRoundFlowLayout_Swift()
//        layout.itemSize = CGSize(width: sectionW/4 - 0.5, height: sectionW/4 - 10)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 6, left: 24, bottom: 16, right: 24)
        return layout
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = titleS
        if let dyA = CacheArr[dyArrParam] {
            dyArr =  dyA
        }
        if let dyD = CacheDic[dyDicParam] {
            dyDic = dyD
        }
        KSLog("开始---")
        KSLog(dyArr)
        KSLog(dyDic)

        addBg()
      initSearch()
        layoutCollectionView()
        getTempMenu(id: moduleID) { arr in
       
            var dyArray = arr
            if DeveloperTool.shared.GetAllowAllLimit() {
                
            } else {
                for i in 0..<dyArray.count {
                    dyArray[i].tempArr = dyArray[i].tempArr.filter{ self.limitIDS.contains($0.res_id.unwrap) || $0.res_id.unwrap == "" || $0.res_id.unwrap == "0" }
                }
                
                
                
////                //  隐藏菜单的隐藏 引用菜单的组装 和模块id的写入
//                for i in 0..<dyArray.count {
//                    dyArray[i].tempArr = configReferMenu4SecondLevel(dyArray[i].tempArr,module_id: "3")
//                }
                
                
            }
            
            for xx in 0..<dyArray.count {
                let tarr = dyArray[xx].tempArr
                var itArr = [MenuItem]()
                for i in 0..<tarr.count {
                    let oneTpX = tarr[i]
                    let onex =  MenuItem(resId: "", title: oneTpX.menu_nm.unwrap, imgStr: "",imgUrl: configURLOK(latter: oneTpX.pic_url.unwrap)) {[oneTpX] parent in
                        var one = oneTpX
                        one.module_id = self.moduleID
                        
                        go2TempUtil(pvc: parent, rtemp: one)
                       
                    }
                    itArr.append(onex)
                }
                KSLog("itArr")
                KSLog(dyArray[xx].directory_nm.unwrap)

                KSLog(itArr)
                self.totalItemList.append((dyArray[xx].directory_nm.unwrap,itArr))
               
            }
            
            self.setMenu()
        }
        
    }
    func addBg() {
    }
    func initSearch() {
        searchBar = TenderSearchBar()
        searchBar!.delegate = self
    }

    
    
    func layoutCollectionView() {
        
        
        self.view.backgroundColor = .white
          
         
        collectionView.dataSource = self
        collectionView.delegate = self
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(getcolltopMargin())
            make.left.right.bottom.equalTo(self.view)
        }
    }
    func setMenu() {
        
   
        for catalogueNm in dyArr {
            if  let memutitles = dyDic[catalogueNm] {
                let showMenuItemList = menuArrDealed(memutitles)
                if showMenuItemList.count > 0 {
                    // 相同目录拼接
                    if let indexx = self.totalItemList.compactMap({ $0.0 }).getIndexFor({ nm in
                        nm == catalogueNm
                    }) {
                        var cuArr = self.totalItemList[indexx].1
                        cuArr += showMenuItemList
                        self.totalItemList[indexx].1 = cuArr
                    } else {
                        // 不同目录另起
                        self.totalItemList.append((catalogueNm, showMenuItemList))
                    }
                
                }
            }
           
        }
        
        
        
       
        dealTempList()
    }
    
}
extension ComDynamicBaseVC:UISearchBarDelegate {
    // 处理过滤事件
    func dealTempList() {
        if keyWord == "" {
            self.tempItemList = self.totalItemList
        } else {
            self.tempItemList.removeAll()
            for item in self.totalItemList {
                let xOne = item.1.filter { $0.title.unwrap.contains(keyWord) }
                if xOne.count > 0 {
                    self.tempItemList.append((item.0, xOne))
                }
            }
            
        }
        collectionView.reloadData()
        
    }
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        keyWord = searchText
        self.dealTempList()
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        
    }
    
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
      
    }
}



// MARK: - 代理和数据源
extension ComDynamicBaseVC {
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FunctionCenterHeader.identifier, for: indexPath) as! FunctionCenterHeader
        header.titleLabel.text = self.tempItemList[indexPath.section].0
        
        
        return header
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: KSGlobal.screenW, height: 40)
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.tempItemList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.tempItemList[section].1.count
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FunctionCenterCell.identifier, for: indexPath as IndexPath) as! FunctionCenterCell
        
        let theone = self.tempItemList[indexPath.section].1[indexPath.row]
        cell.title.text = theone.title.unwrap
        if let img = UIImage(named: self.tempItemList[indexPath.section].1[indexPath.row].title.unwrap) {
            cell.img.image = img
        } else if let img = UIImage(named: self.tempItemList[indexPath.section].1[indexPath.row].imgStr.unwrap) {
            cell.img.image = img
        } else if let imageUrl = URL(string: configURLOK(latter: theone.imgUrl.unwrap)) {
            let resource = KF.ImageResource(downloadURL: imageUrl)
            cell.img.kf.setImage(with: resource, placeholder: UIImage(named:"1_ld"))
  
        } else {
            cell.img.image = UIImage(named:"new_img\(indexPath.row%5 + 1)")
        }
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let oneAc = tempItemList[indexPath.section].1[indexPath.row].enterFunc
        oneAc!(self)
        
        
        
    }
    // 设置itemsize
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let sectionW = self.view.ks_width - 20
        
        if PlatformManager.shared.platform == .zhuYouAn {
            let width = sectionW/3 - 11
            return CGSize(width: width, height: width*0.8)
        } else {
            return CGSize(width: sectionW/4 - 11, height: sectionW/4 - 10)
        }
    }
}

extension ComDynamicBaseVC : JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 12, left: 12, bottom: 12, right: 12)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init()
        model.cornerRadius = 8
        model.backgroundColor = UIColor(kshex:"#f9f9f9")
        
        
        return model;
        
    }
}

// 一级 ，二级菜单的引用菜单组装方法 顺便加入模块id
// 隐藏菜单的隐藏 引用菜单的组装 和模块id的写入
func configReferMenu4SecondLevel(_ oriArr:[MainTempModel],module_id:String) -> [MainTempModel] {
    
    var newArr = [MainTempModel]()
    for y in 0..<oriArr.count {
        let onex = oriArr[y]
        if onex.tempArr.count > 0 {
            
            var onexNew = onex
            // 是个目录
            var newTempArr = [MainTempModel]()
            for m in 0..<onex.tempArr.count {
                var oneZZ = onex.tempArr[m]
                
                if oneZZ.refer_ids.unwrap != "" {
                    let referids = oneZZ.refer_ids.unwrap.components(separatedBy: ",")
                    let referMo = onex.tempArr.filter{ referids.contains($0.id_key.unwrap)  }
                    let referMoMid = referMo.compactMap { oneo in
                        var onen = oneo
                        onen.module_id = module_id
                        return onen
                    }
                    oneZZ.referModels = referMoMid
                }
                oneZZ.module_id = module_id
                
                
#if DEBUG 
                if  TempUDTool.shared.GetShowType() == "1" {
                    
                    newTempArr.append(oneZZ)
                    
                } else {
                    if oneZZ.is_use == "1" {
                        newTempArr.append(oneZZ)
                    }
                }
#else
                if oneZZ.is_use == "1" {
                    newTempArr.append(oneZZ)
                }
#endif
                
                
            }
            onexNew.tempArr = newTempArr
            newArr.append(onexNew)
            
        } else {
            // 是个菜单
            var onexNew = onex
            if onexNew.refer_ids.unwrap != "" {
                let referids = onex.refer_ids.unwrap.components(separatedBy: ",")
                let referMo = oriArr.filter{ referids.contains($0.id_key.unwrap)  }
                let referMoMid = referMo.compactMap { oneo in
                    var onen = oneo
                    onen.module_id = module_id
                    return onen
                }
                onexNew.referModels = referMoMid
            }
            onexNew.module_id = module_id
  
#if DEBUG 
            if  TempUDTool.shared.GetShowType() == "1" {
                newArr.append(onexNew)
            } else {
                if onexNew.is_use == "1" {
                    newArr.append(onexNew)
                }
            }
#else
            if onexNew.is_use == "1" {
                newArr.append(onexNew)
            }
#endif

            
        }
    }
    return newArr
}
